#include "sensor.h"
#include <stdio.h>
#include <string.h>

static int read_float(const char *path, float *out)
{
    FILE *f = fopen(path, "r");
    if (!f) return -1;
    if (fscanf(f, "%f", out) != 1) { fclose(f); return -1; }
    fclose(f);
    return 0;
}

int read_temperature(float *temp)
{
    float scale = 0, offset = 0, raw = 0;
    int r = 0;
    r |= read_float("/sys/bus/iio/devices/iio:device0/in_temp_scale", &scale);
    r |= read_float("/sys/bus/iio/devices/iio:device0/in_temp_offset", &offset);
    r |= read_float("/sys/bus/iio/devices/iio:device0/in_temp_raw", &raw);
    if (r != 0) return -1;
    *temp = (raw + offset) * scale / 1000.0f;
    return 0;
}

int read_humidity(float *hum)
{
    float scale = 0, offset = 0, raw = 0;
    int r = 0;
    r |= read_float("/sys/bus/iio/devices/iio:device0/in_humidityrelative_scale", &scale);
    r |= read_float("/sys/bus/iio/devices/iio:device0/in_humidityrelative_offset", &offset);
    r |= read_float("/sys/bus/iio/devices/iio:device0/in_humidityrelative_raw", &raw);
    if (r != 0) return -1;
    *hum = (raw + offset) * scale / 1000.0f;
    return 0;
}

// Try read a float from first existing path in list
static int read_first_float(const char *const *paths, int n, float *out)
{
    for (int i = 0; i < n; ++i) {
        if (paths[i] && read_float(paths[i], out) == 0) return 0;
    }
    return -1;
}

int read_light(float *lux)
{
    // 优先使用表格指定：iio:device1/in_illuminance_input，其次回退常见路径
    const char *input_paths[] = {
        "/sys/bus/iio/devices/iio:device1/in_illuminance_input",
        "/sys/bus/iio/devices/iio:device0/in_illuminance_input",
        "/sys/bus/iio/devices/iio:device0/in_illuminance0_input",
        "/sys/bus/iio/devices/iio:device0/in_intensity_both_input"
    };
    float v = 0.0f;
    if (read_first_float(input_paths, (int)(sizeof(input_paths)/sizeof(input_paths[0])), &v) == 0) {
        *lux = v;
        return 0;
    }

    // 2) raw + scale forms
    float raw = 0.0f, scale = 0.0f;
    int r = 0;
    // Try illuminance raw+scale
    r = read_float("/sys/bus/iio/devices/iio:device0/in_illuminance_raw", &raw);
    if (r == 0 && read_float("/sys/bus/iio/devices/iio:device0/in_illuminance_scale", &scale) == 0) {
        *lux = raw * scale;
        return 0;
    }
    // Try intensity_both raw+scale
    r = read_float("/sys/bus/iio/devices/iio:device0/in_intensity_both_raw", &raw);
    if (r == 0 && read_float("/sys/bus/iio/devices/iio:device0/in_intensity_both_scale", &scale) == 0) {
        *lux = raw * scale;
        return 0;
    }

    return -1; // not available
}
